import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import nprogress from 'nprogress'

// 检测设备类型
const isMobile = () => {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || 
         window.innerWidth < 768
}

// 获取布局组件
const getLayoutComponent = () => {
  return isMobile() ? 
    () => import('@/layouts/MobileLayout.vue') : 
    () => import('@/layouts/MainLayout.vue')
}

// 获取页面组件（移动端优先）
const getPageComponent = (mobilePath: string, desktopPath: string) => {
  return isMobile() ? 
    () => import(/* @vite-ignore */ mobilePath) : 
    () => import(/* @vite-ignore */ desktopPath)
}

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/LoginView.vue'),
    meta: { requiresGuest: true }
  },
  {
    path: '/register', 
    name: 'Register',
    component: () => import('@/views/auth/RegisterView.vue'),
    meta: { requiresGuest: true }
  },
  {
    path: '/',
    name: 'Layout',
    component: getLayoutComponent(),
    meta: { requiresAuth: true },
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/DashboardView.vue'),
        meta: { title: '控制台' }
      },
      {
        path: 'media',
        name: 'Media',
        children: [
          {
            path: '',
            name: 'MediaList',
            component: () => import('@/views/media/MediaListView.vue'),
            meta: { title: '媒体文件' }
          },
          {
            path: ':id',
            name: 'MediaDetail',
            component: getPageComponent(
              '@/views/mobile/MediaDetailView.vue',
              '@/views/media/MediaDetailView.vue'
            ),
            meta: { title: '媒体详情' }
          },
          {
            path: 'upload',
            name: 'MediaUpload',
            component: () => import('@/views/media/MediaUploadView.vue'),
            meta: { title: '上传文件' }
          },
          {
            path: 'ai-classify',
            name: 'AiClassify',
            component: () => import('@/views/media/AiClassifyView.vue'),
            meta: { title: 'AI智能分类' }
          },
          {
            path: 'album/:id',
            name: 'MediaAlbum',
            component: () => import('@/views/media/MediaAlbumView.vue'),
            meta: { title: '相册详情' }
          }
        ]
      },
      {
        path: 'diary',
        name: 'Diary',
        children: [
          {
            path: '',
            name: 'DiaryList',
            component: () => import('@/views/diary/DiaryListView.vue'),
            meta: { title: '日记本' }
          },
          {
            path: 'write',
            name: 'DiaryWrite',
            component: () => import('@/views/diary/DiaryWriteView.vue'),
            meta: { title: '写日记' }
          },
          {
            path: ':id',
            name: 'DiaryDetail',
            component: () => import('@/views/diary/DiaryDetailView.vue'),
            meta: { title: '日记详情' }
          }
        ]
      },
      {
        path: 'family',
        name: 'Family',
        component: getPageComponent(
          '@/views/mobile/FamilyManageView.vue',
          '@/views/family/FamilyView.vue'
        ),
        meta: { title: '家庭管理' }
      },
      {
        path: 'activity',
        name: 'Activity',
        children: [
          {
            path: '',
            name: 'ActivityList',
            component: () => import('@/views/activity/ActivityListView.vue'),
            meta: { title: '活动管理' }
          },
          {
            path: 'create',
            name: 'ActivityCreate',
            component: () => import('@/views/activity/ActivityCreateView.vue'),
            meta: { title: '创建活动' }
          },
          {
            path: ':id',
            name: 'ActivityDetail',
            component: () => import('@/views/activity/ActivityDetailView.vue'),
            meta: { title: '活动详情' }
          },
          {
            path: ':id/edit',
            name: 'ActivityEdit',
            component: () => import('@/views/activity/ActivityCreateView.vue'),
            meta: { title: '编辑活动' }
          }
        ]
      },
      {
        path: 'settings',
        name: 'Settings',
        component: () => import('@/views/settings/SettingsView.vue'),
        meta: { title: '设置' }
      }
    ]
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/error/Error404View.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

router.beforeEach(async (to, from, next) => {
  nprogress.start()
  
  const authStore = useAuthStore()
  
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  const requiresGuest = to.matched.some(record => record.meta.requiresGuest)
  
  if (requiresAuth && !authStore.isAuthenticated) {
    next({ name: 'Login', query: { redirect: to.fullPath } })
    return
  }
  
  if (requiresGuest && authStore.isAuthenticated) {
    next({ name: 'Dashboard' })
    return
  }
  
  if (to.meta.title) {
    document.title = `${to.meta.title} - 家庭媒体管理系统`
  }
  
  next()
})

router.afterEach(() => {
  nprogress.done()
})

export default router
